#include <iostream>
#include "VTShape.h"

void VTShapePrint(VTShape* pThis)
{
	//通过函数指针调用函数
	pThis->vtable->Print(pThis);
}


// Triangle类的实现

void TrianglePrint(VTShape* pThis)
{
	auto pTriangle = (Triangle_t*)pThis;
	std::cout << "Triangle:" << pTriangle->id << std::endl;
}

// 编译器为每个含有虚函数的class创建一个虚拟函数表
struct TriangleVTable
{
	VTableShape vtable;
	TriangleVTable()
	{
		vtable.Print = &TrianglePrint; // 编译器填写具体的实现函数的指针
	}
};
static TriangleVTable sTriangleVTable; // 一个类只有一个虚函数表，为所有实例共享

void ConstructTriangle(Triangle_t* pThis, int id)
{
	pThis->vtable = &sTriangleVTable.vtable; // 编译器在构造函数中插入初始化代码指向本类的虚拟函数表
	pThis->id = id;
}

// Circle类的实现

void CirclePrint(VTShape* pThis)
{
	auto pCircle = (Circle_t*)pThis;
	std::cout << "Circle" << std::endl;
}

struct CircleVTable
{
	VTableShape vtable;
	CircleVTable()
	{
		vtable.Print = &CirclePrint;
	}
};
static CircleVTable sCircleVTable;

void ConstructCircle(Circle_t* pThis)
{
	pThis->vtable = &sCircleVTable.vtable;
}